#include <iostream>
#include <sys/socket.h> // 必选！socket(), bind(), listen(), accept() 等
#include <netinet/in.h> // 必选！struct sockaddr_in（IPv4 地址结构）
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/types.h> // 必选！socket(), bind(), listen(), accept() 等
#include <string.h>
#include <stdlib.h>
#include <error.h>
#include <stdio.h>
using namespace std;
int main()
{
    int socketfd = socket(AF_INET, SOCK_STREAM, 0);
    if (socketfd < 0)
    {
        perror("socket error");
        return 0;
    }
    // 连接服务器
    struct sockaddr_in addr;
    // addr.sin_addr.s_addr = inet_addr(argv[1]);
    // addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr("192.168.139.129");
    addr.sin_port = htons(8888);
    addr.sin_family = AF_INET;
    while (1)
    {
        int ret = connect(socketfd, (struct sockaddr *)&addr, sizeof(addr));
        if (ret == -1)
        {
            cout << "连接失败"<<endl;
            sleep(1);
            continue;
        }
        break;
    }
    while (1)
    {
        char buf[1024] = {0};
        cin >> buf;
        int len = send(socketfd, buf, strlen(buf), 0);
        if (len == 0)
        {
            cout << "服务端关闭连接" << endl;
            close(socketfd);
            break;
        }
        len = recv(socketfd, buf, sizeof(buf), 0);
        if (len == 0)
        {
            cout << "服务端关闭连接" << endl;
            close(socketfd);
            break;
        }
        cout << buf << endl;
    }
    return 0;
}
